package com.linn.home.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linn.home.dao.RoleMenuDao;
import com.linn.home.entity.Node;
import com.linn.home.dao.RoleDao;
import com.linn.home.entity.Role;
import com.linn.home.entity.RoleMenu;
import com.linn.home.service.RoleMenuService;
import com.linn.home.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色service
 * Created by Administrator on 2018/8/9.
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMenuDao roleMenuDao;

    @Resource
    private RoleDao roleDao;

    @Override
    public PageInfo findRoleList(PageInfo pageInfo) {
        PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
        List<Role> roles = roleDao.findRoleList();
        pageInfo = new PageInfo(roles);
        return pageInfo;
    }

    @Transactional
    @Override
    public int addRole(Role role,String[] menuIds) {

        int index = roleDao.addRole(role);
        int roleId = role.getId();
        if(index > 0){
            addRoleMenu(role,menuIds);
        }
        return 1;
    }

    @Transactional
    @Override
    public int updateRole(Role role,String[] menuIds) {
        int index = roleDao.updateRole(role);
        if(index > 0){
            addRoleMenu(role,menuIds);
        }
        return 1;
    }

    private void addRoleMenu(Role role,String[] menuIds){
        //删除角色菜单
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(role.getId());
        roleMenuDao.deleteRoleMenuByRoleId(roleMenu);

        for (String menuId:menuIds) {
            roleMenu.setMenuId(Integer.valueOf(menuId));
            roleMenuDao.addRoleMenu(roleMenu);
        }
    }

    @Override
    public int deleteRole(Role role) {
        return roleDao.deleteRole(role);
    }

    @Override
    public int batchRemoveRole(int[] ids) {
        for(int id:ids){
            //删除角色菜单
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id);
            roleMenuDao.deleteRoleMenuByRoleId(roleMenu);
        }
        return roleDao.batchRemoveRole(ids);
    }

    @Override
    public Role findRoleById(int id) {
        return roleDao.findRoleById(id);
    }

    @Override
    public List<Node> findRoleMenuList(Integer roleId) {
        return roleDao.findRoleMenuByRoleId(roleId);
    }
}
